package com.msnrobotweb.http;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.LinkedHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.jml.MsnMessenger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.simpleframework.http.Container;
import org.simpleframework.http.Request;
import org.simpleframework.http.Response;
import org.simpleframework.http.connect.Connection;
import org.simpleframework.http.connect.SocketConnection;

import com.msnrobotweb.http.action.PingAction;
import com.msnrobotweb.http.action.PostAction;

/**
 * Robot Server main class.
 * @author bm888888@gmail.com
 *
 */
public class RobotServer implements Container {
  
  private static Log log = LogFactory.getLog(RobotServer.class);
  
  MsnMessenger messenger;
  
  
  private LinkedHashMap<String, HttpAction> actions = new LinkedHashMap<String, HttpAction>();
  
  public RobotServer() {
    
    actions.put("ping", new PingAction());
    actions.put("post", new PostAction());
  }
  
  public RobotServer(  MsnMessenger messenger) {
    
    actions.put("ping", new PingAction());
    actions.put("post", new PostAction());
    
    this.messenger = messenger;
  }
  

  public void handle(Request request, Response response) {
       
    try {
      
      String uri = request.getAddress().getPath().getPath();
      if(log.isDebugEnabled()){
        log.debug(uri);
      }  
  
      HttpAction action = getAction(uri);
      
      if(null == action) {
        
        response.setCode(404);
        
      }else {
        
        RobotRequest request2 = new RobotRequest(messenger,request);
        RobotResponse response2 = new RobotResponse(response);
        action.process(request2, response2); 
        
      }
      
    } catch (Exception e) {
      log.error(e);
      //output 500 error to client      
      response.setCode(500);
      response.setText("500 error");
      
      try {
        response.getPrintStream().print("500 error");
      } catch (Exception e1) {
        log.error(e1);        
      }
      
    }finally {
      response.set("Server", "Powered By Simple Server");
      try {
        response.getPrintStream().close();
      } catch (Exception e) {
        log.error(e); 
      }
    }
    
    
    
  }
  
  protected HttpAction getAction(String URI) {
    
    /**
     * 匹配任意字符但不是/和?
     */
    
    String regex = "\\w+";
    Pattern pattern = Pattern.compile(regex);
    
    Matcher matcher = pattern.matcher(URI);
    
    HttpAction action=null;
    
    String url = null;
    if(matcher.find()){
        url  = URI.substring(matcher.start() , matcher.end());
        
        if(log.isDebugEnabled()){
            log.debug(url);
        }
        
        action = actions.get(url);
        
        if(action ==null){
            if(log.isDebugEnabled()){
                log.debug("Action Not Find");
            }
        }
        
    }
    
    return action;
}

  

  public static void main(String[] list) throws Exception {
    int port = 8080;
    Container container = new RobotServer();
    Connection connection = new SocketConnection(container);
    SocketAddress address = new InetSocketAddress(port);
    connection.connect(address);
    System.out.print("http server started with port:" + port);
  }
}